<template>
<div class="askforinvoicetothefactory">
  <div class="head">
    <div class="btns clearfix">
      <h2>增值税开票信息</h2>
      <!-- <el-button class="export"  :disabled="!editable" type="primary">导出</el-button> -->
    </div>


    <div class="invoice">
      <div class="invoice-title">
        <h3>公 司 名 称 ：天津金贸链进出口有限公司</h3>
        <h3>纳税人识别号：91120118MA05K8NK2E</h3>
        <h3> 地 址：天津自贸试验区（空港经济区）环河南路88号2-2205号</h3>
        <h3>电 话：010-50911255</h3>
        <h3>开 户 银 行 ：中信银行股份有限公司天津自由贸易试验区分行</h3>
        <h3>银 行 账 户 ：8111401011700147295</h3>
        <el-row class="invoice-title__input">
          <el-col :span="3"><h3>收 件 人：</h3></el-col>
          <el-col :span="16">
            <input type="text" @input="handleSimpleInput" v-model="documentprocess_aski_receiver" placeholder="请输入收件人名称" />
          </el-col>
        </el-row>
        <el-row  class="invoice-title__input">
          <el-col :span="3"><h3>邮 政 编 码：</h3></el-col>
          <el-col :span="16">
            <input type="text" @input="handleSimpleInput" v-model="documentprocess_aski_addressCode" placeholder="请输入收件人邮政编码" />
          </el-col>
        </el-row>
        <el-row   class="invoice-title__input">
          <el-col :span="3"><h3>邮寄地址：</h3></el-col>
          <el-col :span="16">
            <input type="text" @input="handleSimpleInput" v-model="documentprocess_aski_address" placeholder="请输入收件人邮寄地址" />
          </el-col>
        </el-row>
      </div>

      <div class="invoice-table">
        <h3>开票内容</h3>

        <el-table :data="documentprocess_aski_table" border style="width: 100%">

          <el-table-column type="index" label="序号" :index="indexMethod"></el-table-column>
          <el-table-column prop="documentprocess_aski_producuts" label="产品" width="180">
            <template slot-scope="scope">
                  <input type="text" @input="handleTableInput(scope, 'documentprocess_aski_producuts', $event)" :readonly="!editable" v-model="scope.row.documentprocess_aski_producuts" />
            </template>
          </el-table-column>
          <el-table-column prop="documentprocess_aski_description" label="规格型号">
            <template slot-scope="scope">
                  <input type="text" @input="handleTableInput(scope, 'documentprocess_aski_description', $event)" :readonly="!editable" v-model="scope.row.documentprocess_aski_description" />
            </template>
          </el-table-column>

          <el-table-column prop="documentprocess_aski_price" label="单价" >
            <template slot-scope="scope">
                  <input type="number" @input="handleTableInput(scope, 'documentprocess_aski_price', $event)" :readonly="!editable" v-model="scope.row.documentprocess_aski_price" />
            </template>
          </el-table-column>

          <el-table-column prop="documentprocess_aski_quantity" label="数量">
            <template slot-scope="scope">
                  <input type="number" @input="handleTableInput(scope, 'documentprocess_aski_quantity', $event)" :readonly="!editable" v-model="scope.row.documentprocess_aski_quantity" />
            </template>
          </el-table-column>

          <el-table-column prop="documentprocess_aski_unit" label="单位">
            <template slot-scope="scope">
                  <input type="text" @input="handleTableInput(scope, 'documentprocess_aski_unit', $event)" :readonly="!editable" v-model="scope.row.documentprocess_aski_unit" />
            </template>
          </el-table-column>
          <el-table-column prop="documentprocess_aski_lineAmount" label="总价">
            <template slot-scope="scope">
                  <input type="text" @input="handleTableInput(scope, 'documentprocess_aski_lineAmount', $event)" :readonly="!editable" v-model="scope.row.documentprocess_aski_lineAmount" />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100" v-if="editable">
            <template slot-scope="scope">
            <el-button @click="addNewLine(scope.$index, documentprocess_aski_table)" type="text" size="small">添加</el-button>
            <el-button @click="removeCurrentLine(scope.$index, documentprocess_aski_table)" type="text" size="small">移除</el-button>
          </template>
          </el-table-column>
        </el-table>
      </div>
    </div>


    <div class="upload">
      <p class="upload-hint">票据/附件</p>
      <div>
        <div class="upload-btn">
          <input type="file"  v-show="editable"  name="file" multiple @change="selectFiles">
          <el-button :disabled="!editable" type="primary">选择附件</el-button>
        </div>

        <ul class="upload-files">
          <li @mouseover="handleOver(item)" :key="index"  @mouseout="handleOut(item)" v-for="(item,index) in attachedFiles">
            <span @click="download(item.id, $event)">{{item.name}}</span>
            <span v-if="editable && item.status" class="el-icon-circle-check" style="color:#67c23a;"></span>
            <span v-else-if="editable" class="el-icon-circle-close" @click="changeFiles(index,item)" style="color:red;"></span>
          </li>
        </ul>
      </div>
    </div>
  </div>


</div>
</template>

<script>
import { uploadFiles } from "@/server/initiatingprocess";
import { filedownload, deleteFile } from "@/server/customermanagement/index.js";
import {
  getData,
  getSendMenus,
  getOrderNumber
} from "@/server/initiatingprocess";

import { getStore, setStore, removeStore } from "@/assets/js/common.js";
import {toFixed} from '@/util/transform.js';

export default {
  created() {
    this.keys.forEach(key => {
      this[key] = _.cloneDeep(this.datas[key]);
    }); 
  },
  updated() {
  },

  mounted(){

    let self = this;
    
    //接收报关单 表格整体改变
    this.bus.$on("documentprocess_askInvoice-table-all", function(arg){
      let srcTable = arg[0], destTable = [];
      for (let i = 0; i < srcTable.length; i ++) {
          destTable[i] = {
            documentprocess_aski_producuts:  srcTable[i].documentprocess_cc_df_productName,
            documentprocess_aski_description: srcTable[i].documentprocess_cc_df_productDesc,
            documentprocess_aski_price: srcTable[i].documentprocess_cc_df_price ,
            documentprocess_aski_quantity: srcTable[i].documentprocess_cc_df_quantityAndUnit[0] ,
            documentprocess_aski_unit:  srcTable[i].documentprocess_cc_df_quantityAndUnit[1] ,
            documentprocess_aski_lineAmount: srcTable[i].documentprocess_cc_df_amount
          };
      }
      self.documentprocess_aski_table = destTable;
      self.emitToParent();
    })

    //接收报关单 表格 添加或者删除
    this.bus.$on("documentprocess_askInvoice-table", function(arg){

      let index = arg[1], srcData = arg[2];
      if (arg[0] === 'add') {
          //添加
          let  data = {
            documentprocess_aski_producuts:  srcData.documentprocess_cc_df_productName,
            documentprocess_aski_description: srcData.documentprocess_cc_df_productDesc,
            documentprocess_aski_price: srcData.documentprocess_cc_df_price ,
            documentprocess_aski_quantity: srcData.documentprocess_cc_df_quantityAndUnit[0] ,
            documentprocess_aski_unit:  srcData.documentprocess_cc_df_quantityAndUnit[1] ,
            documentprocess_aski_lineAmount: srcData.documentprocess_cc_df_amount
          }; 

          if ((index - self.documentprocess_aski_table.length) >= 1) {
            self.documentprocess_aski_table.push(data);
          } else {
            self.documentprocess_aski_table.splice(index, 0, data);
          }

        } else if(arg[0] === 'delete'){
          //删除
          if (self.documentprocess_aski_table.length - 1 >= index) {
            self.documentprocess_aski_table.splice(index, 1);
          }
        }
        self.emitToParent();
    });


    // //接收报关单 表格输入
    this.bus.$on("documentprocess_askInvoice-table-line", function(arg){
        let index = arg[0], key = self.prevMapCur[arg[1]], value = arg[2];

        if (index  <= (self.documentprocess_aski_table.length - 1)) {
          let temp = _.cloneDeep(self.documentprocess_aski_table[index]), result;
          
          switch(key){
            case 'documentprocess_aski_producuts':
            case 'documentprocess_aski_description':
            case 'documentprocess_aski_unit':
            temp[key] = value;
            break;
            

            case 'documentprocess_aski_price':
            temp[key] = toFixed(value);
            result  = Number(temp[key]) * Number(temp.documentprocess_aski_quantity);
            temp.documentprocess_aski_lineAmount = toFixed(self.handleIsNaN(result));
            break;

            case 'documentprocess_aski_quantity':
            temp[key] = self.handleIsNaN(parseInt(value));
            result  = Number(temp[key]) * Number(temp.documentprocess_aski_price);
            temp.documentprocess_aski_lineAmount = toFixed(self.handleIsNaN(result));
            break;

            case 'documentprocess_aski_lineAmount':
            temp.documentprocess_aski_lineAmount = toFixed(value);
            break;
          }
          self.documentprocess_aski_table.splice(index, 1, temp);
          self.emitToParent();
        }
    });

  },
  methods: {
    /** 
     * 更新数据到单证员报关
    */
    emitToParent(){
      let obj = {};
      this.keys.forEach(key => {
        obj[key] = this[key];
      });

      this.$emit("fromAI", "documentprocess_askInvoice", obj);
    },

    handleSimpleInput(){
      this.emitToParent();
    },


    /**
     * 处理NaN的数据
     */
    handleIsNaN(value){
      if (Number.isNaN(value)){
        return 0;
      } else {
        return value;
      }
    },

    /**
     * 处理表格的输入
     */
    handleTableInput(scope, key, value){
      let oldData = _.cloneDeep(this.documentprocess_aski_table[scope.$index]), temp = 0;

      switch(key){
        case 'documentprocess_aski_price':
        if (/^\d+\.?\d{0,2}$/.test(event.target.value)) {
           oldData[key] =  event.target.value;
        } else {
           oldData[key] =  toFixed(event.target.value);
        }
        temp = Number(oldData.documentprocess_aski_quantity) * Number(oldData.documentprocess_aski_price);
        oldData.documentprocess_aski_lineAmount = toFixed(this.handleIsNaN(temp));
        this.documentprocess_aski_table.splice(scope.$index, 1, oldData);
        break;

        case 'documentprocess_aski_quantity':
        oldData.documentprocess_aski_quantity =  Number.isNaN(parseInt(event.target.value).toString()) ? '0' : parseInt(event.target.value).toString();
        temp = Number(oldData.documentprocess_aski_quantity) * Number(oldData.documentprocess_aski_price);
        oldData.documentprocess_aski_lineAmount = toFixed(this.handleIsNaN(temp));
        this.documentprocess_aski_table.splice(scope.$index, 1, oldData);
        break;

        case 'documentprocess_aski_lineAmount':
        if (/^\d+\.?\d{0,2}$/.test(event.target.value)) {
           oldData[key] =  event.target.value;
        } else {
           oldData[key] =  toFixed(event.target.value);
        }
        this.documentprocess_aski_table.splice(scope.$index, 1, oldData);
        break;
      }

      this.emitToParent();
    },

    indexMethod(value) {
      return value + 1;
    },

    selectFiles(event) {
      //票据附件
      let self = this;

      //直接上传，并且获得后端返回的文件的url,将url保存到 this.data.attachedFiles中
      uploadFiles(event.target.files).then(resArr => {
        resArr.forEach(function(res, i) {
          self.attachedFiles.push({
            name: event.target.files[i].name,
            status: 1,
            id: res.data.datas[0].id
          });
          self.emitToParent();
        });
      });
    },
    changeFiles(index, item) {
      deleteFile({ id: item.id }).then(res => {
        if (res.code != 1) {
          this.$message.error("删除失败，请检查网络后重试");
        } else {
          this.attachedFiles.splice(index, 1);
          this.emitToParent();
        }
      });
    },
    handleOver(item) {
      item.status = 0;
      this.$forceUpdate();
    },
    handleOut(item) {
      item.status = 1;
      this.$forceUpdate();
    },
    download(id, event) {
      window.open("http://47.104.93.41/api/common/download?id=" + id);
    },
    addNewLine(currentIndex, table) {
      let lastLine = _.cloneDeep(table[currentIndex]), newLine = {};

      let keys = [
          "documentprocess_aski_producuts",
          "documentprocess_aski_description",
          "documentprocess_aski_price",
          "documentprocess_aski_quantity",
          "documentprocess_aski_unit",
          "documentprocess_aski_lineAmount"
      ];

      keys.forEach(key => {
        newLine[key] = lastLine[key];
      });
      table.splice(currentIndex + 1, 0, newLine);
      this.emitToParent();
    },
    removeCurrentLine(currentIndex, table) {
      if (table.length > 1) {
        table.splice(currentIndex, 1);
       this.emitToParent();
      }
    }
  },

  data() {
    return {
      id: '',
      formInstId: '',
      attachedFiles: [],
      documentprocess_aski_receiver: '',
      documentprocess_aski_addressCode: '',
      documentprocess_aski_address: '',

      //发票信息
      documentprocess_aski_table: [
        {
          documentprocess_aski_producuts: '',
          documentprocess_aski_description: '',
          documentprocess_aski_price: '',
          documentprocess_aski_quantity: '',
          documentprocess_aski_unit: '',
          documentprocess_aski_lineAmount: ''
        }
      ],
      keys: [
        "id",
        "formInstId",
        "attachedFiles",
        "documentprocess_aski_receiver",
        "documentprocess_aski_addressCode",
        "documentprocess_aski_address",
        "documentprocess_aski_table"

      ],

      prevMapCur: {
        "documentprocess_cc_df_productName": 'documentprocess_aski_producuts',
        "documentprocess_cc_df_productDesc": 'documentprocess_aski_description',
        "documentprocess_cc_df_price": 'documentprocess_aski_price',
        "documentprocess_cc_df_quantityAndUnit-0": 'documentprocess_aski_quantity',
        "documentprocess_cc_df_quantityAndUnit-1": 'documentprocess_aski_unit',
        "documentprocess_cc_df_amount": 'documentprocess_aski_lineAmount'
      }
    };
  },

  watch: {
    datas(newValue, oldValue){
      this.keys.forEach(key => {
        this[key] = _.cloneDeep(newValue[key]);
      });
    }
  },
  props: {
    datas: {
      type: Object,
      required: true
    },
    editable: {
      type: Boolean,
      required: true
    },
    bus: {
      type: Object,
      required: true
    }
  }
};
</script>

<style lang="scss">
.askforinvoicetothefactory {
  padding: 20px;


  .select-currency {
      select {
        margin-left: 12px;
        height: 30px;
        width: 60px;
      }
  }

  border: 1px solid #999;
  .head {
    .btns {
      width: 100%;
      height: 80px;
      text-align: center;
      .export {
        float: right;
      }
    }

    .invoice {
      .invoice-title {
        > h3 {
          padding: 15px 0;
          > p {
            padding: 15px 0;
          }
        }

        .invoice-title__input {
          line-height: 40px;

          margin-bottom: 10px;

          input {
            width: 240px;
            height: 36px;
            border-radius: 2px;
            border: 1px solid  #e6ebf5;
          }
        }
      }

      .invoice-table {
        > h3 {
          padding: 20px 0;
        }

        input {
              border: none;
              outline: none;
              background-color: transparent;
             height: 100%;
        }


        .el-table__body-wrapper {
          overflow: hidden;
        }

        .el-table {
          margin-bottom: 20px;

          td {
            border: 1px solid #e6ebf5;
          }
        }

        .el-input__inner {
          border: none;
          background: transparent;
          padding: 0;
          text-align: center;
        }

        .el-input-number__decrease,
        .el-input-number__increase {
          width: 20px;

          border: none;
          background: transparent;
        }

        .el-input-number {
          width: 100%;
          min-width: 80px;
        }
      }
    }

    .upload {
      > div {
        border: 1px solid #999;
        padding: 20px 0 40px 20px;
      }

      .upload-btn {
        position: relative;
        > input {
          opacity: 0;
          width: 100px;
          height: 40px;
          position: absolute;
          top: 0;
          left: 0;
        }
      }

      .upload-files {
        > li {
          width: 300px;
          padding: 10px 0;
          transition: all 0.5s linear;

          &:hover {
            > span {
              color: #409eff;
            }
          }
        }

        font-size: 16px;
        span {
          padding: 0 10px;
          cursor: pointer;
          display: inline;
        }
        span.el-icon-close:hover {
          cursor: pointer;
        }
      }
      .upload-hint {
        font-size: 20px;
        margin-bottom: 10px;
      }
    }
  }
}
</style>
